package com.lt.bigevent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lt.bigevent.entity.Category;
import com.lt.bigevent.entity.User;
import com.lt.bigevent.service.CategoryService;
import com.lt.bigevent.util.ThreadLocalUtil;
import com.lt.bigevent.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping("/add")
    public Result<String> add(@RequestBody @Validated(Category.Add.class) Category category){
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("userId");
        Category category1 = new Category();
        category1.setUpdateTime(new Date());
        category1.setCategoryName(category.getCategoryName());
        category1.setCategoryAlias(category.getCategoryAlias());
        category1.setCreateTime(new Date());
        category1.setCreateUser(id);
        categoryService.save(category1);
        return Result.success();
    }

    @GetMapping("/list")
    public Result<List<Category>> list(){
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("userId");
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getCreateUser,id);
        List<Category> cs = categoryService.list(wrapper);
        return Result.success(cs);
    }

    @GetMapping("/detail")
    public Result<Category> detail(Integer id){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getId,id);
        Category c = categoryService.getOne(wrapper);
        return Result.success(c);
    }

    @PostMapping("/update")
    public Result<String> update(@RequestBody @Validated(Category.Update.class) Category category){
        LambdaUpdateWrapper<Category> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Category::getCategoryName,category.getCategoryName());
        wrapper.set(Category::getCategoryAlias,category.getCategoryAlias());
        wrapper.set(Category::getUpdateTime,new Date());
        wrapper.eq(Category::getId,category.getId());
        categoryService.update(wrapper);
        return Result.success();
    }

    @PostMapping("/delete")
    public Result delete(Integer id){
        LambdaUpdateWrapper<Category> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Category::getId,id);
        categoryService.remove(wrapper);
        return Result.success();
    }
}
